package cn.loioi.util.poi.read;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.loioi.util.poi.exception.ReadExcelException;

public class ReadRow<T> {
	private int row;
	private Object obj;
	private List<ReadExcelException> errors;

	public ReadRow(int row) {
		this.row = row;
	}

	public static <M> ReadRow<M> newInstance(int row, Class<M> clazz) throws InstantiationException, IllegalAccessException {
		ReadRow<M> readRow = new ReadRow<>(row);
		if (clazz.isInstance(Map.class)) {
			readRow.obj = new HashMap<String, Object>();
		} else {
			readRow.obj = clazz.newInstance();
		}
		return readRow;
	}

	public int row() {
		return row;
	}

	@SuppressWarnings("unchecked")
	public T obj() {
		return (T) obj;
	}

	public List<ReadExcelException> errors() {
		return errors;
	}

	public ReadRow<T> addError(ReadExcelException error) {
		if (this.errors == null) this.errors = new ArrayList<>();
		this.errors.add(error);
		return this;
	}

	public ReadRow<T> addError(int cell, Object obj, String message) {
		return addError(new ReadExcelException(message, row, cell, obj));
	}

	@SuppressWarnings("unchecked")
	public ReadRow<T> set(String feild, Object object) throws ReflectiveOperationException, IntrospectionException {
		if (obj instanceof Map) {
			((Map<String, Object>) obj).put(feild, object);
		} else {
			PropertyDescriptor pd = new PropertyDescriptor(feild, obj.getClass());
			pd.getWriteMethod().invoke(obj, object);
		}
		return this;
	}
}
